package org.example.blog_system.service;

import org.example.blog_system.mapper.BlogMapper;
import org.example.blog_system.mapper.UserMapper;
import org.example.blog_system.model.BlogInfo;
import org.example.blog_system.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class BlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private UserMapper userMapper ;

    public List<BlogInfo> getList(){
        List<BlogInfo> list = this.blogMapper.getList();
        //修改 blog的长度
        for(BlogInfo blogInfo : list){
            if(blogInfo.getContent().length() > 100){
                blogInfo.setContent(blogInfo.getContent().substring(0,100)+"...");
            }
        }
        return  list ;
    }

    public BlogInfo getBlog(Integer blogId){
        BlogInfo blogInfo = blogMapper.getBlog(blogId);
      return blogInfo ;
    }

    public boolean setBlog(HttpSession session ,BlogInfo blogInfo) {
        if( !StringUtils.hasLength(blogInfo.getContent()) || !StringUtils.hasLength(blogInfo.getTitle()) ||
        session == null){
            return false ;
        }


        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        blogInfo.setUserid(userInfo.getUserid());
        blogMapper.setBlog(blogInfo);
        return true ;
    }

    public boolean updateBlog(BlogInfo blogId) {
        Integer n =  blogMapper.updateBlog(blogId);
        return n==1 ;
    }

    public boolean deleteBlog(Integer blogId ) {
        Integer n = blogMapper.deleteBlog(blogId) ;
        return  n == 1;
    }

    public Integer getBlogByUser(HttpSession session , Integer blogId) {
        if(session == null || session.getAttribute("userInfo")==null){
            return  0 ;
        }
       Integer n = 0 ;
        if(blogId == null){
            UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
            n = blogMapper.getBlogByUser(userInfo);
        }else {
            UserInfo userInfo =  userMapper.getUserByBlogId(blogId);
            n = blogMapper.getBlogByUser(userInfo);
        }
        return n==null?0:n;
    }
}
